//
//  PayViewController.swift
//  BaseSwift
//
//  Created by gh on 2019/10/5.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit

class PayViewController: UIViewController {

    var lastPayBtn:UIButton? = nil
    var order:OrderVo?
    let warnLab = UILabel()
    var minus = 0.00
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        self.navigationView.setTitle("订单支付")
        
        self.navigationView.removeAllLeftButton()
        self.navigationView.addLeftButton(with: UIImage(named: "nav_back")) { (view) in
            
            APP.initMainVC()
        }
        
        let topView = UIView()
        view.addSubview(topView)
        topView.backgroundColor = UIColor.white

        let _ = topView.sd_layout()?.widthRatioToView(view,1)!.heightIs(100)!.topSpaceToView(view,HT_StatusBarAndNavigationBarHeight)
        let priceLab = UILabel()
        topView.addSubview(priceLab)
        priceLab.text = "￥\(self.order!.amountAll!)"
        priceLab.textColor = UIColor.btnMainColor
        priceLab.font = UIFont.systemFont(ofSize: 32, weight: UIFont.Weight(rawValue: 0.2))
        priceLab.textAlignment = .center
        let _ = priceLab.sd_layout()?.widthRatioToView(topView,1)!.heightIs(25)!.topSpaceToView(topView,24)
        
        let time = self.order?.payOverTime?.split(string: "T").first
        let time1 = self.order?.payOverTime?.split(string: "T")[1].split(string: ".").first
        let time2 = time! + " "+time1!
        
        let date2 = NSDate.br_get(time2, format: "yyyy-MM-dd HH:mm:ss")! as NSDate
        
         minus = date2.minutesLaterThan(NSDate() as Date)
        
        
        

        topView.addSubview(warnLab)
        warnLab.textColor = UIColor.tabbarDefaultTextColor
        warnLab.font = UIFont.smallerFont
        warnLab.text = "支付剩余时间:0秒"
        warnLab.textAlignment = .center
        let _ = warnLab.sd_layout()?.widthRatioToView(topView,1)!.heightIs(20)!.topSpaceToView(priceLab,15)
        
        self.timeChange()
        
        let payView = UIView()
        payView.backgroundColor = UIColor.white
        view.addSubview(payView)
        payView.sd_cornerRadius = 8

        let _ = payView.sd_layout()?.leftSpaceToView(view,12)!.rightSpaceToView(view,12)!.heightIs(160)!.topSpaceToView(topView,16)
        
        let zfbBtn = UIButton()
        payView.addSubview(zfbBtn)
        zfbBtn.setTitle("支付宝", for: .normal)
        zfbBtn.addTarget(self, action: #selector(payBtnClick), for: .touchUpInside)
        zfbBtn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
        zfbBtn.titleLabel?.font = UIFont.commonFontSmall
        zfbBtn.setImage(UIImage(named: "支付宝"), for: .normal)
        let _ = zfbBtn.sd_layout()?.widthRatioToView(payView,1)!.heightIs(80)!.topSpaceToView(payView,0)
        let _ = zfbBtn.imageView?.sd_layout()?.widthIs(28)!.heightIs(28)!.centerYEqualToView(zfbBtn)!.leftSpaceToView(zfbBtn,16)
        let _ = zfbBtn.titleLabel?.sd_layout()?.leftSpaceToView(zfbBtn.imageView,16)
        
        let rightIcon1 = UIImageView()
        zfbBtn.addSubview(rightIcon1)
        rightIcon1.tag = 9909
        rightIcon1.image = UIImage(named: "selected")
        let _ = rightIcon1.sd_layout()?.widthIs(25)!.heightIs(25)!.centerYEqualToView(zfbBtn)!.rightSpaceToView(zfbBtn,16)
        lastPayBtn = zfbBtn

        
        let line = UIView()
        line.backgroundColor = UIColor.backgroundColor
        zfbBtn.addSubview(line)
        let _ = line.sd_layout()?.heightIs(1)!.widthRatioToView(zfbBtn,1)!.bottomSpaceToView(zfbBtn,0)
        
        let wxBtn = UIButton()
        payView.addSubview(wxBtn)
        wxBtn.addTarget(self, action: #selector(payBtnClick), for: .touchUpInside)

        wxBtn.setTitle("微信", for: .normal)
        wxBtn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
        wxBtn.titleLabel?.font = UIFont.commonFontSmall
        wxBtn.setImage(UIImage(named: "微信支付"), for: .normal)
        let _ = wxBtn.sd_layout()?.widthRatioToView(payView,1)!.heightIs(80)!.topSpaceToView(zfbBtn,0)
        let _ = wxBtn.imageView?.sd_layout()?.widthIs(28)!.heightIs(28)!.centerYEqualToView(wxBtn)!.leftSpaceToView(wxBtn,16)
        let _ = wxBtn.titleLabel?.sd_layout()?.leftSpaceToView(wxBtn.imageView,16)
        
        let rightIcon = UIImageView()
        wxBtn.addSubview(rightIcon)
        rightIcon.tag = 9909
        rightIcon.image = UIImage(named: "unselected")
        let _ = rightIcon.sd_layout()?.widthIs(25)!.heightIs(25)!.centerYEqualToView(wxBtn)!.rightSpaceToView(wxBtn,16)


        
        let commitBtn = UIButton()
        commitBtn.addTarget(self, action: #selector(commitClick), for: .touchUpInside)
        view.addSubview(commitBtn)
        commitBtn.sd_cornerRadius = LARAGE_BTN_RADIUS
        let _ = commitBtn.sd_layout()?.leftSpaceToView(view,24)?.rightSpaceToView(view,24)?.heightIs(LARAGE_BTN_HEIGHT)?.centerXEqualToView(view)?.bottomSpaceToView(view,20+HT_TabbarSafeBottomMargin)
        commitBtn.gradientBtnMainColor()
        
        let tlab = UILabel()
        tlab.text = "确认支付"
        tlab.font = UIFont.titleFont
        tlab.textColor = UIColor.white
        tlab.textAlignment = .center
        commitBtn.addSubview(tlab)
        let _ = tlab.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        
        
        
        
        
    }
    //倒计时
    func timeChange() {
        
        var time:Double = minus*60
        let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: DispatchQueue.global())
        codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))  //此处方法与Swift 3.0 不同
        codeTimer.setEventHandler {
            
            time = time - 1
            
            DispatchQueue.main.async {
                
            }
            
            if time < 0 {
                codeTimer.cancel()
                DispatchQueue.main.async {
                    //self.skipButton.isEnabled = true
                    //self.skipButton.setTitle("重新发送", for: .normal)
                    codeTimer.cancel()

                    
                }
                return
            }
            
    
            DispatchQueue.main.async {
                let str = self.secondsToTimeString(seconds: Int(time))
                self.warnLab.text = "支付剩余时间:\(str)"
            }
            
            
        }
        
        codeTimer.activate()
        
    }
    func secondsToTimeString(seconds: Int) -> String {
        //天数计算
        //let days = (seconds)/(24*3600);
        
        //小时计算
        let hours = (seconds)%(24*3600)/3600;
        
        //分钟计算
        let minutes = (seconds)%3600/60;
        
        //秒计算
        let second = (seconds)%60;
        
        let timeString  = String(format: "%02lu小时%02lu分%02lu秒", hours, minutes, second)
        return timeString
    }

    @objc func payBtnClick(btn:UIButton){
        
        let rigicon = btn.viewWithTag(9909) as! UIImageView
        rigicon.image = UIImage(named: "selected")
        
        if lastPayBtn != btn{
            
            let rigicon = lastPayBtn!.viewWithTag(9909) as! UIImageView
                rigicon.image = UIImage(named: "unselected")
            
        }
        lastPayBtn = btn
        
    }
    @objc func commitClick(){
        
        var type = "ALIPAY"
        if lastPayBtn?.titleLabel?.text == "支付宝" {
            
            type = "ALIPAY"
            
        }else{
            
            type = "WECHAT"
        }
        API.payOrder(params: ["payType":type,
                              "orderNo":self.order!.orderNo!]) { (result) in
            
            
                                if type == "ALIPAY"{
                                    
                                    //支付宝支付
                                                    AlipaySDK.defaultService()?.payOrder((result as! String), fromScheme: "goodplace", callback: { (dic) in
                                        
                                        
                                        if (dic!["resultStatus"] as! String) == "9000"{
                                            
                                            APP.paySuccess!()
                                            
                                        }else{
                                            
                                            ToastUtil.showHUDError(msg: "用户主动取消支付")
                                        }
                                        
                                    })
                                    
                                                    
                                    APP.paySuccess = {() in
                                        
                                        
                                        let vc = PayResultVC()
                                        vc.type = "ALIPAY"
                                        vc.order = self.order
                                        PUSH(from: self, to: vc)
                                        
                                    }
                                }else{
                                    
                                    let str =  result as! String
                                    let dic = str.toDictionary()
                                    self.startWeiChatPay(dic: dic)
                                                    
                                    APP.paySuccess = {() in
                                        
                                        let vc = PayResultVC()
                                        vc.order = self.order
                                        vc.type = "WECHAT"
                                        PUSH(from: self, to: vc)

                                    }
                                }

        }
        
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    func startWeiChatPay(dic:NSDictionary) {
        
        let req = PayReq()
        req.openID = dic.object(forKey: "appid") as! String
        req.partnerId = dic.object(forKey: "partnerid") as! String
        req.prepayId = dic.object(forKey: "prepayid") as! String
        req.nonceStr = dic.object(forKey: "noncestr") as! String
        req.timeStamp = dic.object(forKey: "timestamp") as! UInt32
        req.package = dic.object(forKey: "package") as! String
        req.sign = dic.object(forKey: "sign") as! String
        WXApi.send(req)
        
    }

}
